import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.io.FileUtils;
import org.apache.http.client.fluent.Request;

/**
 * 用这个，很不错。或者Main也行。
 * 
 * @author Larry
 *
 */
public class Main4 {
	private static final String TOKEN = "optionOn";

	public static void main(String[] args) {
		String URL = needUrl();
		//
		if (String.join(",", args).contains(TOKEN)) {
			System.out.println("是否开始访问该网站？Y/N");
			@SuppressWarnings("resource")
			Scanner sc = new Scanner(System.in);
			String tell = sc.nextLine();
			if (!tell.equalsIgnoreCase("y")) {
				System.out.println("你没有选择Y，程序现在自动退出，再见！");
				return;
			}
			System.out.println("你选择Y，程序现在开始通过代理访问目标网址！");
		}
		//

		System.out.println("开始读取文件");
		String currentPath = Main4.class.getResource("/").getPath();
		if (currentPath.contains(":")) {
			currentPath = currentPath.substring(1);
		}
		String name = currentPath + "Proxy.txt";
		List<String> proxies = null;
		try {
			System.out.println("读取文件中...");
			proxies = FileUtils.readLines(new File(name));
			System.out.println("读取完毕！");
		} catch (IOException e1) {
			System.out.println("读取失败！请检查文件是否存在！[" + name + "]");
			return;
		}

		///
		System.out.println("开始验证...");
		Map<String, String> map = new ConcurrentHashMap<>();

		proxies.parallelStream().forEach((e) -> {
			try {
				int code = Request.Get(URL).connectTimeout(3000).socketTimeout(3000).viaProxy(e).execute().returnResponse().getStatusLine()
						.getStatusCode();
				if (code == 200) {
					map.put(e, "");
					System.out.println(">>>代理[" + e + "]有效！");
				} else {
					System.out.println("代理[" + e + "]无效！");
				}
			} catch (IOException e1) {
				System.out.println("代理[" + e + "]无效！");
			}
		});

		System.out.println("验证结束！");
		System.out.println(">>>>>>>>>>>>>>>成功次数为：" + map.size() + "<<<<<<<<<<<<<<<");

		///
		try {
			System.out.println("开始将可用代理写入原文件中...");
			FileUtils.writeLines(new File(name), map.keySet());
			System.out.println("写入成功！");
		} catch (IOException e2) {
			System.out.println("写入失败！请检查是否有权限写入该文件。");
		}
		System.out.println("执行完毕！");
		// System.exit(0);
	}

	public static String needUrl() {
		System.out.println("请输入要访问的网址：");
		@SuppressWarnings("resource")
		Scanner sc = new Scanner(System.in);
		String url = sc.nextLine();
		url = url.trim();
		if (url.isEmpty()) {
			needUrl();
		}
		return url;
	}
}
